#include "qhttphelper.h"

#define LOG()  qDebug() << __LINE__

QHttpHelper::QHttpHelper(QObject *parent) : QObject(parent)
{
    LOG() << __FUNCTION__;
}

QByteArray QHttpHelper::syncGet(QString geturl,QStringList paramList,int timeout)
{
    QStringList params = paramList;

    qSort(params.begin(), params.end());
    auto param = params.join("&");

    auto url = geturl + param;
    QFuture<QByteArray> worker = QtConcurrent::run(this,&QHttpHelper::get, url,timeout);
    worker.waitForFinished();
    auto rec = worker.result();

    return rec;
}

QByteArray QHttpHelper::get(const QString &strUrl, int timeout)
{
    Q_ASSERT(!strUrl.isEmpty());

    QNetworkAccessManager qnam;
    const QUrl url = QUrl::fromUserInput(strUrl);
    Q_ASSERT(url.isValid());

    QNetworkRequest qnr(url);

    if("https" == url.scheme()){
        QSslConfiguration conf = qnr.sslConfiguration();
        conf.setPeerVerifyMode(QSslSocket::VerifyNone);
        conf.setProtocol(QSsl::TlsV1SslV3);
        qnr.setSslConfiguration(conf);
    }

    QNetworkReply* reply = qnam.get(qnr);

    QTimer timer;
    QEventLoop eventLoop;
    connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    timer.start(timeout); //超时
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);

    QByteArray replyData = reply->readAll();
    reply->deleteLater();
    reply = nullptr;

    return replyData;
}

